function distEclud(vecA,vecB){
	var sum = 0;
	for(var i = 0;i < vecA.length;i++){
		var deta = vecA[i] - vecB[i];
		sum = sum + deta * deta;
	}

	return Math.sqrt(sum);
}

function randCent(dataSet,k){
	// var minJ = [];
	// var rangJ = [];
	// for(var i = 0;i < dataSet[0].length;i++){
	// 	var min = dataSet[0][i];
	// 	var max = dataSet[0][i];
	// 	for(var j = 0;j < dataSet.length;j++){
	// 		if(dataSet[j][i] < min){
	// 			min = dataSet[j][i];
	// 		}
	// 		if (dataSet[j][i] > max) {
	// 			max = dataSet[j][i];
	// 		}
	// 	}
	// 	minJ.push(min);
	// 	rangJ.push(max - min);
	// }
	var centroids = []
	for(var i = 0;i < k;i++) {
		centroids.push(dataSet[Math.round(Math.random() * dataSet.length)]);
	}
	return centroids;
}

function kMeans(dataSet,k){
	var m = dataSet.length;
	var clusterAssment0 = [];
	for(var i = 0;i < m;i++){
		clusterAssment0.push(0);
	}
	var centroids = randCent(dataSet,k);
	var clusterChanged = true;
	console.log('length ==>', distEclud(centroids[1],dataSet[0]));
	while(clusterChanged){
		clusterChanged = false;
		let isError = false;
		for(var i = 0;i < m;i++){
			var minDist = Number.MAX_VALUE;
			var minIndex = 0;

			for(var j = 0;j < k;j++){
				var distJI = distEclud(centroids[j],dataSet[i]);
				if(distJI < minDist){
					minDist = distJI;
					minIndex = j;
				}
			}
			if(clusterAssment0[i] != minIndex && !isError){
				clusterChanged = true;
			}
			clusterAssment0[i] = minIndex;
		}
		let tmp = {};
		for (let j = 0; j < m; j++) {
			if (tmp[clusterAssment0[j]] === undefined) {
				tmp[clusterAssment0[j]] = { len: 0, data: [] };
			}
			tmp[clusterAssment0[j]].len++;
			tmp[clusterAssment0[j]].data.push(dataSet[j]);
		}
		for (let key in tmp) {
			let center = [];
			for (let i = 0; i < tmp[key].data.length; i++) {
				const data = tmp[key].data[i];
				for (let j = 0; j < data.length; j++) {
					if (center[j] === undefined) {
						center[j] = 0;
					}
					center[j] += data[j];
				}
			}
			for (let j = 0; j < center.length; j++) {
				center[j] = center[j] / tmp[key].data.length;
			}
			centroids[key] = center;
		}
	}
	return {
		centroids:centroids,
		cluster:clusterAssment0
	};
}

export default kMeans;
